<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Base64 数据转换与展示</title>
</head>

<body>
    <!-- 上传 Base64 数据的 txt 文件 -->
    <h2>上传 Base64 数据的 txt 文件</h2>
    <input type="file" id="base64TxtInput" accept=".txt">
    <button onclick="convertFromTxt()">转换</button>
    <div id="mediaDisplay"></div>

    <!-- 上传图片或视频文件转换为 Base64 -->
    <h2>上传图片或视频转换为 Base64</h2>
    <input type="file" id="mediaFileInput" accept="image/*,video/*">
    <button onclick="convertToBase64()">转换</button>
    <textarea id="base64Output" rows="10" cols="50" readonly></textarea>

    <script>
        function convertFromTxt() {
            const txtInput = document.getElementById('base64TxtInput');
            const file = txtInput.files[0];
            const mediaDisplay = document.getElementById('mediaDisplay');

            if (!file) {
                alert('请选择一个 txt 文件');
                return;
            }

            const reader = new FileReader();
            reader.onload = function (e) {
                const base64Data = e.target.result.trim();

                // 先尝试解析为图片
                const img = new Image();
                img.src = `data:image/jpeg;base64,${base64Data}`;
                img.onload = function () {
                    mediaDisplay.innerHTML = '';
                    mediaDisplay.appendChild(img);
                    return;
                };
                img.onerror = function () {
                    // 不是图片，尝试解析为视频
                    const video = document.createElement('video');
                    video.width = 320;
                    video.height = 240;
                    video.controls = true;
                    video.src = `data:video/mp4;base64,${base64Data}`;
                    video.onloadeddata = function () {
                        mediaDisplay.innerHTML = '';
                        mediaDisplay.appendChild(video);
                    };
                    video.onerror = function () {
                        alert('无法识别为有效的图片或视频数据');
                    };
                };
            };
            reader.readAsText(file);
        }

        function convertToBase64() {
            const mediaInput = document.getElementById('mediaFileInput');
            const file = mediaInput.files[0];
            const base64Output = document.getElementById('base64Output');

            if (!file) {
                alert('请选择一个图片或视频文件');
                return;
            }

            const reader = new FileReader();
            reader.onload = function (e) {
                const base64Data = e.target.result.split(',')[1];
                base64Output.value = base64Data;
            };
            reader.readAsDataURL(file);
        }
    </script>
</body>

</html>